package com.cheetah.start.system.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheetah.start.common.utils.MySecurityUtil;
import com.cheetah.start.system.admin.domain.SysAdmin;
import com.cheetah.start.system.admin.mapper.SysAdminMapper;
import com.cheetah.start.system.admin.service.SysAdminService;
import com.cheetah.start.system.role.domain.SysRoleAdmin;
import com.cheetah.start.system.role.service.SysRoleAdminService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Feel
 * @create 2021/7/18
 **/
@AllArgsConstructor
@Service
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements SysAdminService {

    @Autowired
    private SysRoleAdminService roleAdminService;

    @Override
    public SysAdmin getByName(String name) {
        QueryWrapper<SysAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        return getOne(wrapper);
    }

    @Override
    public boolean saveWithRoleIds(SysAdmin sysAdmin) {
        save(sysAdmin);
        boolean b = roleAdminService.saveBySysAdmin(sysAdmin);
        return b;
    }


    @Override
    public boolean updateByIdWithRole(SysAdmin sysAdmin) {
        if (StrUtil.isNotBlank(sysAdmin.getPassword())) {
            sysAdmin.setPassword(MySecurityUtil.encode(sysAdmin.getPassword()));
        } else {
            sysAdmin.setPassword(null);
        }
        boolean b = updateById(sysAdmin);
        roleAdminService.removeByAdminId(sysAdmin.getAdminId());
        roleAdminService.saveBySysAdmin(sysAdmin);
        return b;
    }

    @Override
    public boolean isRepeat(SysAdmin sysAdmin) {
        QueryWrapper<SysAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("name", sysAdmin.getName());
        if (sysAdmin.getAdminId() != null) {
            wrapper.ne("admin_id", sysAdmin.getAdminId());
        }
        List<SysAdmin> list = list(wrapper);
        return CollUtil.isNotEmpty(list);
    }

    @Override
    public void setRoleIds(List<SysAdmin> records) {
        if (CollUtil.isNotEmpty(records)) {
            for (SysAdmin record : records) {
                List<SysRoleAdmin> roleAdmins = roleAdminService.listByAdminId(record.getAdminId());
                if (CollUtil.isNotEmpty(roleAdmins)) {
                    for (SysRoleAdmin roleAdmin : roleAdmins) {
                        record.getRoleList().add(roleAdmin.getRoleId());
                    }
                }
            }
        }
    }
}
